/*
 * =====================================================================================
 *
 *       Filename:  udp_recv.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年05月22日 11时30分57秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <libnyb/libnyb-net.h>

int main(int argc, char **argv)
{
    if(argc != 2) {
        printf("Usage: %s streamnum\n", argv[0]);
        return 0;
    }

    int i;
    int stream_num = atoi(argv[1]);
    int *fd = (int *)calloc(stream_num, sizeof(int));
    if(NULL == fd) {
        perror("calloc()");
        return 0;
    }
    for(i = 0; i < stream_num; i++) {
        fd[i] = udpsock_create("192.168.1.100", 15060 + 2*i);
        if(fd[i] < 0) {
            continue;
        }
        if(sock_set_nonblock(fd[i]) < 0) {
            close(fd[i]);
            fd[i] = 0;
            continue;
        }
    }
    while(1) {
        struct sockaddr addr;
        socklen_t addrlen;
        char buff[2048] = {0};
        for(i = 0; i < stream_num; i++) {
            if(fd[i] > 0) {
                int len;
                if((len = recvfrom(fd[i], buff, sizeof(buff), 0, &addr, &addrlen)) < 0) {
                    if(errno != EAGAIN) {
                        fprintf(stderr, "recvfrom: 192.168.1.1:%d %s\n", 15060 + 2*i, strerror(errno));
                    }
                }
                else {
                    printf("%d bytes from 192.168.1.1:%d\n", len, 15060 + 2*i);
                }
            }
        }
    }
    return 0;
}

